from peewee import *
from playhouse.pool import PooledMySQLDatabase

# 连接到 MySQL 数据库
database = PooledMySQLDatabase(
    'ruoyi',
    max_connections=10,
    stale_timeout=300,
    host=3306,
    port='127.0.0.1',
    user='root',
    password='root'
)


# 定义数据模型
class InfoReptileData(Model):
    id = BigAutoField(primary_key=True)  # 将类型改为 BigAutoField
    title = CharField()
    author = CharField()
    synopsis = CharField()
    info_sources = CharField()
    info_url = CharField()
    release_time = DateTimeField()
    create_time = DateTimeField()
    content = TextField()
    cover = CharField()

    class Meta:
        database = database
        table_name = 'info_reptile_data'


class InfoReptileDataContent(Model):
    id = BigAutoField(primary_key=True)  # 将类型改为 BigAutoField
    info_id = CharField()
    content = TextField()
    sort_id = CharField(null=True)
    create_time = DateTimeField(null=True)
    update_time = DateTimeField(null=True)

    class Meta:
        database = database
        table_name = 'info_reptile_data_content'


def close_data_base():
    # 关闭数据库连接
    database.close()


# 定义方法插入数据到 info_reptile_data 表并返回插入数据的id
def insert_info_reptile_data(data):
    if database.is_closed():
        # 连接数据库
        database.connect()
    # 创建表（如果不存在）
    database.create_tables([InfoReptileData])
    try:
        with database.atomic():
            info_reptile_data = InfoReptileData.create(**data)
            inserted_id = info_reptile_data.id
            return inserted_id
    except Exception as e:
        print(f"Failed to insert data into 'info_reptile_data': {str(e)}")
        return None


# 定义方法插入数据到 info_reptile_data_content 表并返回插入数据的id
def insert_info_reptile_data_content(data):
    if database.is_closed():
        # 连接数据库
        database.connect()
    database.create_tables([InfoReptileDataContent])
    try:
        with database.atomic():
            info_reptile_data_content = InfoReptileDataContent.create(**data)
            inserted_id = info_reptile_data_content.id
            return inserted_id
    except Exception as e:
        print(f"Failed to insert data into 'info_reptile_data_content': {str(e)}")
        return None